﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Bll;
using Runda.CMS.Common.Entity;
using Runda.CMS.Common.Utility;
using System.Collections.Generic;

namespace Runda.CMS.Portal.ContractFollowUp
{
    public partial class MaintainImport : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void lnkbtnSaveAndClose_Click(object sender, EventArgs e)
        {           
            if (fileupload.HasFile) {
                string isXls = System.IO.Path.GetExtension(fileupload.FileName).ToString().ToLower();
                if (isXls != ".xls" && isXls != ".xlsx")
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('导入文件格式不正确');", true);
                    return; 
                }
                string fileName = fileupload.FileName;
                fileupload.PostedFile.SaveAs(Server.MapPath("\\Temp") + "\\" + fileName);
                string filepath = Server.MapPath("\\Temp") + "\\" + fileName;  
                try
                {
                    DataTable dt = ExcelImport.ExcelToDT(filepath, "sheet1");
                    for (int index = 0; index < dt.Rows.Count; index++) {
                        string customerName = dt.Rows[index]["客户名称"].ToString().Trim();
                        string instrumentCode = dt.Rows[index]["仪器编号"].ToString().Trim();
                        string instrumentSerialNum = dt.Rows[index]["序列号"].ToString().Trim();
                        string installDate = dt.Rows[index]["安装日期"].ToString().Trim();
                        string InstrumentBeginUse = dt.Rows[index]["开始使用日期"].ToString().Trim();
                        string GuaranteeInfo = "";
                        if (dt.Rows[index]["保修情况"].ToString() == "厂家保修")
                        {
                            GuaranteeInfo = System.Convert.ToInt32(Enumerator.GuaranteeType.ManufactureMaintain).ToString();
                        }
                        if (dt.Rows[index]["保修情况"].ToString() == "商业保修")
                        {
                            GuaranteeInfo = System.Convert.ToInt32(Enumerator.GuaranteeType.BusinessMaintain).ToString();
                        }
                        if (dt.Rows[index]["保修情况"].ToString() == "保修期外")
                        {
                            GuaranteeInfo = System.Convert.ToInt32(Enumerator.GuaranteeType.OverMaintain).ToString();
                        }
                        if (dt.Rows[index]["保修情况"].ToString() == "保修期限")
                        {
                            GuaranteeInfo = System.Convert.ToInt32(Enumerator.GuaranteeType.OnMaintain).ToString();
                        }
                        string WarrantyFrom = dt.Rows[index]["保修开始日期"].ToString();
                        string WarrantyTo = dt.Rows[index]["保修截止日期"].ToString();
                        string GuaranteeFrequency = dt.Rows[index]["保养频率（月）"].ToString();
                        string ReturnVisitFrequency = dt.Rows[index]["回访频率（月）"].ToString();
                        string CalibrationFrequency = dt.Rows[index]["校准频率（月）"].ToString();
                        string CompanyInstrumentCode = dt.Rows[index]["仪器公司编号"].ToString();
                        string SoftWareVersion = dt.Rows[index]["软件版本"].ToString();
                        string ServiceContract = "";
                        //if (dt.Rows[index]["服务合同类型"].ToString() == "全保") {
                        //    ServiceContract = System.Convert.ToInt32(Enumerator.ContractServiceType.All).ToString();
                        //}
                        //if (dt.Rows[index]["服务合同类型"].ToString() == "保人工 ") {
                        //    ServiceContract = System.Convert.ToInt32(Enumerator.ContractServiceType.ForLabor).ToString();
                        //}
                        //if (dt.Rows[index]["服务合同类型"].ToString() == "仅保养") {
                        //    ServiceContract = System.Convert.ToInt32(Enumerator.ContractServiceType.OnlyMaintain).ToString();
                        //}
                        //if (dt.Rows[index]["服务合同类型"].ToString() == "暂无")
                        //{
                        //    ServiceContract = System.Convert.ToInt32(Enumerator.ContractServiceType.None).ToString();
                        //}
                        string HasTrainCertificate = "";
                        if (dt.Rows[index]["是否发放培训证书"].ToString() == "是")
                        {
                            HasTrainCertificate = "1";
                        }
                        else {
                            HasTrainCertificate = "0";
                        }
                        string HasReadNum = "";
                        if (dt.Rows[index]["是否存在读数"].ToString() == "是")
                        {
                            HasReadNum = "1";
                        }
                        else
                        {
                            HasReadNum = "0";
                        }
                        string ReadNumType = "";
                        if (dt.Rows[index]["读数方式"].ToString() == "计数总数")
                        {
                            ReadNumType = "1";
                        }
                        else if ((dt.Rows[index]["读数方式"].ToString() == "读数日平均数"))
                        {
                            ReadNumType = "2";
                        }
                        else { ReadNumType = "0"; }
                        using (System.Transactions.TransactionScope trans = new System.Transactions.TransactionScope())
                        {
                            try
                            {
                                SystemBll bll = new SystemBll();

                                //注册单
                                WsmTaskRegisterEntity entity = new WsmTaskRegisterEntity();
                                entity.RegisterID = Guid.NewGuid();
                                List<CtrtCustomerEntity> customers = bll.GetAll<CtrtCustomerEntity>(" and CustomerName like '%" + customerName.Trim() + "%'");
                                if (customers != null && customers.Count > 0)
                                {
                                    entity.CustomerID = customers[0].CustomerID;
                                }
                                else {
                                    txtResult.Text += "客户【" + customerName + "】不存在,导入被忽略(出错行：" + (index+2).ToString() + ")\r\n";
                                    continue;
                                }
                                List<WsmInstrumentInfoEntity> instruments = bll.GetAll<WsmInstrumentInfoEntity>(" and InstrumentCode like '%"+instrumentCode+"%'");
                                if (instruments != null && instruments.Count > 0)
                                {
                                    entity.InstrumentID = instruments[0].InstrumentID;
                                }
                                else {
                                    txtResult.Text += "仪器【" + instrumentCode + "】不存在,导入被忽略(出错行：" + (index + 2).ToString() + ")\r\n";
                                    continue;
                                }

                                if (instrumentSerialNum == "")
                                {
                                    txtResult.Text += "仪器【" + instrumentCode + "】序列号为空,导入被忽略(出错行：" + (index + 2).ToString() + ")\r\n";
                                    continue;
                                }
                                List<WsmInstrumentAssemblyEntity> instrumentsForCheck = bll.GetAll<WsmInstrumentAssemblyEntity>(" and SerialNum = '" + instrumentSerialNum + "'");
                                if (instrumentsForCheck != null && instrumentsForCheck.Count > 0) {
                                    txtResult.Text += "仪器【" + instrumentCode + "】序列号：" + instrumentSerialNum + "已存在,导入被忽略(出错行：" + (index + 2).ToString() + ")\r\n";
                                    continue;
                                }
                                entity.InstrumentSerialNum = instrumentSerialNum.Trim();
                                entity.PerformPerson = CurrentUserID;
                                entity.CreatedOn = DateTime.Now;
                                entity.CreatedBy = CurrentUserID;
                                entity.Deleted = false;
                                entity.TaskStatus = 1;
                                entity.TaskType = 1;

                                //服务单基本
                                WsmMaintainBillEntity maintainEntity = new WsmMaintainBillEntity();
                                maintainEntity.MaintainID = Guid.NewGuid();
                                maintainEntity.CreatedBy = CurrentUserID;
                                maintainEntity.CreatedOn = DateTime.Now;
                                maintainEntity.InstrumentSerialNum = instrumentSerialNum;
                                maintainEntity.RegisterID = entity.RegisterID;
                                maintainEntity.InstrumentSerialNum = instrumentSerialNum;
                                maintainEntity.Deleted = 0;
                                maintainEntity.GuaranteeInfo = GuaranteeInfo;
                                maintainEntity.Maintainer = CurrentUserID;
                                
                                //装机明细
                                WsmInstrumentAssemblyEntity assemblyEntity = new WsmInstrumentAssemblyEntity();
                                assemblyEntity.AssemblyID = Guid.NewGuid();
                                assemblyEntity.CompanyInstrumentCode = CompanyInstrumentCode;
                                assemblyEntity.Deleted = false;
                                if(DataValid.IsNumeric(GuaranteeFrequency))
                                {
                                    assemblyEntity.GuaranteeFrequency = System.Convert.ToInt32(GuaranteeFrequency);
                                }
                                if (DataValid.IsNumeric(CalibrationFrequency))
                                {
                                    assemblyEntity.CalibrationFrequency = System.Convert.ToInt32(CalibrationFrequency);
                                }

                                assemblyEntity.GuaranteeInfo = GuaranteeInfo;
                                assemblyEntity.HasReadNum = System.Convert.ToInt32(HasReadNum);
                                assemblyEntity.HasTrainCertificate = System.Convert.ToInt32(HasTrainCertificate);
                                if (installDate != null && installDate !="")//DataValid.IsDate(installDate)
                                {
                                    assemblyEntity.InstallDate = System.Convert.ToDateTime(installDate);
                                    maintainEntity.BeginDate = System.Convert.ToDateTime(installDate);
                                    maintainEntity.EndTime = System.Convert.ToDateTime(installDate);
                                }
                                else
                                {
                                    txtResult.Text += "仪器安装日期格式有误,导入被忽略(出错行：" + (index + 2).ToString() + ")\r\n";
                                    continue;
                                }
                                if (InstrumentBeginUse !=null && InstrumentBeginUse!="") //DataValid.IsDate(InstrumentBeginUse)
                                {
                                    assemblyEntity.InstrumentBeginUse = System.Convert.ToDateTime(InstrumentBeginUse);
                                }
                                else
                                {
                                    txtResult.Text += "仪器开始使用日期格式有误,导入被忽略(出错行：" + (index + 2).ToString() + ")\r\n";
                                    continue;
                                }
                                if (DataValid.IsNumeric(ReturnVisitFrequency))
                                {
                                    assemblyEntity.ReturnVisitFrequency = System.Convert.ToInt32(ReturnVisitFrequency);
                                }
                                assemblyEntity.SerialNum = instrumentSerialNum;
                                assemblyEntity.SoftWareVersion = SoftWareVersion;
                                if (DataValid.IsDate(WarrantyFrom))
                                {
                                    assemblyEntity.WarrantyFrom = System.Convert.ToDateTime(WarrantyFrom);
                                }
                                if (DataValid.IsDate(WarrantyTo))
                                {
                                    assemblyEntity.WarrantyTo = System.Convert.ToDateTime(WarrantyTo);
                                }
                                //assemblyEntity.ServiceContract = ServiceContract;
                                assemblyEntity.MaintainID = maintainEntity.MaintainID;
                                assemblyEntity.InstrumentStatus = "1";

                                //读数 
                                WsmInstrumentRecordEntity recordEntity = new WsmInstrumentRecordEntity();
                                recordEntity.InstrumentID = entity.InstrumentID;
                                recordEntity.CreatedBy = CurrentUserID;
                                recordEntity.CreatedOn = DateTime.Now;
                                recordEntity.CustomerID = entity.CustomerID;
                                recordEntity.DailyNum = 0;
                                recordEntity.Deleted = false;
                                recordEntity.MaintainID = maintainEntity.MaintainID;
                                recordEntity.ReadNumType = System.Convert.ToInt32(ReadNumType);
                                recordEntity.RecordDate = DateTime.Now;
                                recordEntity.Recorder = CurrentUserID;
                                recordEntity.RecordID = Guid.NewGuid();
                                recordEntity.SerialNum = instrumentSerialNum;
                                recordEntity.TotalNum = 0;

                                bll.Insert(entity);
                                bll.Insert(maintainEntity);
                                bll.Insert(assemblyEntity);
                                //bll.Insert(recordEntity);
                            }
                            catch (Exception ex)
                            {
                                txtResult.Text += ",导入失败(出错行：" + (index + 2).ToString() + ")，错误提示："+ex.Message+"\r\n";
                                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + ex.Message + ",导入中断(出错行：" + (index + 2).ToString() + ")')", true);

                            }
                            finally
                            {
                                trans.Complete();
                            }
                        }
                    }
                    ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('导入完成!');", true);
                }
                catch(Exception ex) {
                    txtResult.Text += ",导入失败，错误提示：" + ex.Message + "\r\n";
                    ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + ex.Message + "');", true);
                    return;
                }
            }
        }
    }
}
